var exp = require('express');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var fs = require('fs');
var multer = require('multer');

var app = exp();

app.use(exp.static('www'));
app.use(bodyParser.urlencoded({extended:false}));
app.use(cookieParser());

// =================注册======================
app.post('/user/register', (req, res)=>{
    // console.log(req.body);
    req.body.ip = req.ip;
    req.body.time = new Date();

    function send(code, message) {
        res.json({code, message});
    }

    function saveFile() {
        var filename = `users/${req.body.petname}.txt`;

        fs.exists(filename, function (exists) {
            if (exists) {
                send('registered', '该用户名被占用');
            } else {
                fs.appendFile(filename, JSON.stringify(req.body), function (err) {
                    if (err) {
                        send('file error', '抱歉，系统错误，写入失败！');
                    } else {
                        send('success', '恭喜，注册成功！请登录...');
                    }
                });
            }
        });
    }

    fs.exists('users', function (exists) {
        if (exists) {
            saveFile();
        } else {
            fs.mkdirSync('users', function (err) {
                if (err) {
                    send('file error', '抱歉，系统错误');
                } else {
                    console.log('创建成功')                    
                }
            });
            saveFile();
        }
    });
});

// ====================登录=========================
app.post('/user/signin', (req, res)=>{
    var filename = `users/${req.body.petname}.txt`;

    function send(code, message) {
        res.json({code, message});
    }

    fs.exists(filename, function (exists) {
        if (exists) {
            fs.readFile(filename, function (err, data) {
               if (err) {
                   send('file error' , '抱歉，系统错误');
               } else {
                   var user = JSON.parse(data);
                   if (user.password == req.body.password) {
                       res.cookie('petname', req.body.petname);
                       send('success', '登录成功');
                   } else {
                       send('signin error', '密码错误');
                   }
               } 
            });
        } else {
            send('register error', '该用户未注册');
        }
    });
});

// ==============提问===============
app.post('/ask', (req, res)=>{
    var petname = req.cookies.petname;
    if (!petname) {
        send('signin error', '请重新登录...');
        return;
    }

    function send(code, message) {
        res.json({code, message});
    }

    var time = new Date();
    req.body.petname = petname;
    req.body.ip = req.ip;
    req.body.time = time;
    console.log(req.body);

    function saveFile() {
        var filename = `questions/${time.getTime()}.txt`;

        fs.appendFile(filename, JSON.stringify(req.body), function(err){
            if (err) {
                send('file error', '抱歉，系统错误...');
            } else {
                send('success', '问题提交成功！');
            }
        });
    }

    fs.exists('questions', function(exists){
        if (exists) {
            saveFile();
        } else {
            fs.mkdir('questions', function(err){
                if (err) {
                    send('file error', '抱歉，系统错误...');
                } else {
                    saveFile();
                }
            });
        }
    });
});

// ==============回答==============
app.post('/answer', (req, res)=>{
    var petname = req.cookies.petname;

    function send(code, message) {
        res.json({code, message});
    }

    if (!petname) {
        send('signin error', '请重新登录...');
        return;
    }
    // 回答问题时，存入问题文件的文件名通过请求体提交到后台
    // 所以这里可以读取出来
    console.log(req.body);
    var filename = `questions/${req.body.question}.txt`;
    console.log(filename);

    req.body.petname = petname;
    req.body.ip = req.ip;
    req.body.time = new Date();

    fs.readFile(filename, (err, data)=>{
        if (err) {
            send('file error', '抱歉，系统错误...');
        } else {
            var question = JSON.parse(data);
            if (!question.answers) {
                question.answers = [];
            }

            question.answers.push(req.body);

            fs.writeFile(filename, JSON.stringify(question), function(err){
                if (err) {
                    send('file error', '抱歉，系统错误...');
                } else {
                    send('success', '回答提交成功！');
                }
            });
        }
    });
});

// ===============首页================
app.get('/questions', (req, res)=>{
    function send(code, message, data) {
        res.json({code, message, data});
    }

    function readFiles(i, files, questions, complete) {
        if (i < files.length) {
            console.log(`questions/${files[i]}`);
            fs.readFile(`questions/${files[i]}`, function(err,data){
                if (!err) {
                    questions.push(JSON.parse(data));
                }
                // 递归调用
                // i的值需要先增加1再传入readFiles，所以用++i
                readFiles(++i, files, questions, complete);
            });
        } else {
            // 所有文件内容读取完毕后调用 complete
            // 调用它的作用是把读取到所有内容返回到浏览器端
            complete();
        }
    }

    fs.readdir('questions', (err, files)=>{
        if (err) {
            send('file error', '抱歉，系统错误...');
        } else {
            // files：所有文件的名称组成的数组
            console.log(files);
            files = files.reverse();

            var questions = [];
            // 调用自定义函数readFiles
            readFiles(0, files, questions, function(){
                send('success', '读取数据成功！', questions);
            });
        }
    });
});

app.listen(3000, ()=>{console.log('服务器启动成功！');});